package com.peanut.service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import org.springframework.stereotype.Service;

import com.peanut.model.Resource;
import com.peanut.model.ResourceTreeNode;

@Service
public class ResourceTreeMaker {

	public List<ResourceTreeNode> create(List<Resource> moduleList) {
		List<ResourceTreeNode> treeList = makeRoot(moduleList);
		return treeList;
	}

	private List<ResourceTreeNode> makeRoot(List<Resource> moduleList) {
		List<ResourceTreeNode> treeList = new ArrayList<ResourceTreeNode>();
		for (Resource module : moduleList) {
			if (module.getParentId() == null || module.getParentId() == 0) {
				ResourceTreeNode treeNode = new ResourceTreeNode();
				treeNode.setId(module.getId());
				treeNode.setAction(module.getAction());
				treeNode.setText("<font size='2'>"+module.getName()+"</font>");
				treeNode.setDescription(module.getDescription());
				treeNode.setParentId(0);
				treeNode.setEnabled(module.getEnabled());
				treeNode.setIsDisplay(module.getIsDisplay());
				treeNode.setName(module.getName());
				treeNode.setType(module.getType());
				treeNode.setOrderNumber(module.getOrderNumber());
				treeNode.setOpenView(module.getOpenView());
				treeList.add(treeNode);
				makeChildren(moduleList, module, treeNode);
			}
		}
		return treeList;
	}
	
	private void makeChildren(List<Resource> moduleList, Resource nodeModule, ResourceTreeNode treeNode) {
		for (Resource module : moduleList) {
			if (module.getParentId() != null && module.getParentId() == nodeModule.getId()) {
				if (treeNode.getChildren() == null) {
					treeNode.setChildren(new LinkedHashSet<ResourceTreeNode>());
				}
				ResourceTreeNode childNode = new ResourceTreeNode();
				childNode.setId(module.getId());
				childNode.setAction(module.getAction());
				childNode.setText("<font size='2'>"+module.getName()+"</font>");
				childNode.setDescription(module.getDescription());
				childNode.setParentId(treeNode.getId());
				childNode.setEnabled(module.getEnabled());
				childNode.setIsDisplay(module.getIsDisplay());
				childNode.setName(module.getName());
				childNode.setType(module.getType());
				childNode.setOrderNumber(module.getOrderNumber());
				childNode.setOpenView(module.getOpenView());
				treeNode.getChildren().add(childNode);
				treeNode.setLeaf(false);
				makeChildren(moduleList, module, childNode);
			}
		}
	}
}
